import { asyncRoutes, constantRoutes } from '@/router'
import { config } from '@/utils/config'
import Layout from '@/layout'
const _import = require('@/router/_import_' + process.env.NODE_ENV) // 获取组件的方法

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, menus) {
  console.log('filterAsyncRoutes')
  const result = []
  if (config.openPermission && menus) {
    menus.forEach(route => {
      let component = route.component
      if (component) {
        component = route.component.trim()
        if (component) {
          if (component === 'Layout') {
            route.component = Layout
          } else {
            if (component[0] === '/') {
              component = component.substring(1)
            }
            route.component = _import(component) // 导入组件
          }
        }
        if (route.children && route.children.length) {
          route.children = filterAsyncRoutes(routes, route.children)
        }
        result.push(route)
      }
    })
    return result
  } else {
    return routes
  }
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menus) {
    return new Promise(resolve => {
      let accessedRoutes = []
      accessedRoutes = filterAsyncRoutes(asyncRoutes, menus)
      console.log(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
